package com.tieba.controller;


import com.tieba.pojo.Result;
import com.tieba.pojo.User;
import com.tieba.service.UserService;
import com.tieba.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class loginController {

    @Autowired
    private UserService userService;

    //用户登录
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        log.info("用户登录，user:{}",user);
        User loginUser = userService.login(user);
        if (loginUser != null) {
            Map<String, Object> claims = new HashMap<>(); //键值对容器
            claims.put("id", loginUser.getId()); //添加数据id
            claims.put("username", loginUser.getUsername()); //添加数据 用户名

            String jwt = JwtUtils.generateJwt(claims); //生成jwt令牌
            log.info("用户{}登录成功！",user.getUsername());
            return Result.success(jwt);
        }

        return Result.error("用户名或密码错误！");
    }


    //注册用户，选择注册管理员还是用户
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名或密码输入为空！");
        }
        log.info("注册用户 user:{}", user);

        User register = userService.register(user);
        return (register == null?Result.success():Result.error("用户名已注册！"));
    }
}
